package courseController

import (
	"CMETO/models"
	"CMETO/utils"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type CourseController struct{}

// @Summary 课程查询
// @Description 查询课程
// @Tags 课程管理
// @Accept json
// @Produce json
// @Param page query string false "页码"
// @Param pageSize query string false "尺寸"
// @Param name query string false "课程名"
// @Success 200 {object} models.ResultCommon[[]models.Course] "查询成功"
// @Success 400 {object} models.ErrorResult "查询失败"
// @Router /course [get]
// @Security JWT
func (course CourseController) QueryCourses(ctx *gin.Context) {
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
	nameStr := ctx.DefaultQuery("name", "")
	name := "%" + nameStr + "%"
	courseList := []models.CourseFormat{}
	models.DB.Table("courses").
		Select("courses.*, course_types.name AS tname").
		Joins("LEFT JOIN course_types ON courses.tid = course_types.id").
		Where("courses.is_delete!=1 AND courses.name like ?", name).
		Group("courses.id").
		Limit(pageSize).Offset(pageSize * (page - 1)).
		Scan(&courseList)
	var total int64
	models.DB.Table("courses").Where("is_delete!=1 AND name like ?", name).Count(&total)
	result := &models.ResultByPage[models.CourseFormat]{
		Msg:      "ok",
		Code:     "200",
		Total:    total,
		Page:     page,
		PageSize: pageSize,
		Result:   courseList,
	}
	ctx.JSON(http.StatusOK, result)
}

// @Summary 课程新增
// @Description 新增课程
// @Tags 课程管理
// @Accept json
// @Produce json
// @Param deptInfo body models.Course true "课程信息"
// @Success 200 {object} models.AddResult "新增成功"
// @fail 400 {object} models.ErrorResult "数据错误"
// @fail 401 {object} models.AddResult "新增失败"
// @Router /course [post]
// @Security JWT
func (d CourseController) AddCourse(ctx *gin.Context) {
	course := &models.CourseFormat{}
	// 绑定json数据
	if err := ctx.ShouldBindJSON(&course); err != nil {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "数据错误",
			Code:   "400",
			Result: nil,
		})
	} else {
		course.CreateTime = utils.TimeFormatter(time.Now())
		result := models.DB.Transaction(func(tx *gorm.DB) error {
			if r1 := tx.Model(&course.Course).Create(&course.Course).Error; r1 != nil {
				return r1
			}
			course_teacher := &models.CourseTeacher{}
			tx.Where("course_id = ?", course.Id).Delete(&course_teacher)
			for i := 0; i < len(course.Teacher_ids); i++ {
				if r2 := tx.Model(&models.CourseTeacher{}).Create(&models.CourseTeacher{
					CourseId:  course.Id,
					TeacherId: course.Teacher_ids[i],
				}).Error; r2 != nil {
					return r2
				}
			}
			return nil
		})
		if result != nil {
			ctx.JSON(http.StatusOK, &models.AddResult{
				Msg:    "新增失败",
				Code:   "400",
				Result: 0,
			})
		} else {
			ctx.JSON(http.StatusOK, &models.AddResult{
				Msg:    "新增成功",
				Code:   "200",
				Result: 1,
			})
		}
	}
}

// @Summary 课程修改
// @Description 修改课程
// @Tags 课程管理
// @Accept json
// @Produce json
// @Param deptInfo body models.Course true "课程信息"
// @Success 200 {object} models.UpdateResult[models.Course] "更新成功"
// @fail 400 {object} models.ErrorResult "数据错误"
// @fail 401 {object} models.AddResult "修改失败"
// @Router /course [put]
// @Security JWT
func (d CourseController) UpdateCourse(ctx *gin.Context) {
	var course models.CourseFormat
	// 绑定json数据
	if err := ctx.ShouldBindJSON(&course); err != nil {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "数据绑定失败",
			Code:   "400",
			Result: err,
		})
		return
	}
	course_old := &models.Course{}

	models.DB.First(&course_old, course.Id)
	course_old = course.Course
	if course_old.Id == 0 {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "更新失败",
			Code:   "400",
			Result: nil,
		})
	} else {
		result := models.DB.Transaction(func(tx *gorm.DB) error {
			if r1 := tx.Model(&course_old).Save(&course_old).Error; r1 != nil {
				return r1
			}
			course_teacher := &models.CourseTeacher{}
			tx.Where("course_id = ?", course.Id).Delete(&course_teacher)
			for i := 0; i < len(course.Teacher_ids); i++ {
				if r2 := tx.Model(&models.CourseTeacher{}).Create(&models.CourseTeacher{
					CourseId:  course.Id,
					TeacherId: course.Teacher_ids[i],
				}).Error; r2 != nil {
					return r2
				}
			}
			return nil
		})
		if result != nil {
			ctx.JSON(http.StatusOK, &models.ErrorResult{
				Msg:    "更新失败",
				Code:   "400",
				Result: nil,
			})
		} else {
			ctx.JSON(http.StatusOK, &models.UpdateResult[models.CourseFormat]{
				Msg:    "更新成功",
				Code:   "200",
				Result: course,
			})
		}
	}
}

// @Summary 删除课程
// @Description 传入json，批量删除课程
// @Tags 课程管理
// @Accept json
// @Produce json
// @Param deptsIds body models.DeleteParams true "课程id合集"
// @Success 200 {object} models.DeleteResult "更新成功"
// @fail 400 {object} models.ErrorResult "数据错误"
// @fail 401 {object} models.DeleteResult "删除失败"
// @Router /course [delete]
// @Security JWT
func (d CourseController) DeleteCourse(ctx *gin.Context) {
	// 绑定参数实例
	ids := &models.DeleteParams{}
	// 定义模型实例
	var course models.Course
	if err := ctx.ShouldBindJSON(&ids); err != nil {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "删除失败",
			Code:   "400",
			Result: err,
		})
	} else {
		// 假的删
		result := models.DB.Model(&course).Where("id IN (?)", ids.Ids).Update("is_delete", 1)
		if result.RowsAffected != 0 {
			ctx.JSON(http.StatusOK, &models.DeleteResult{
				Msg:    "删除成功",
				Code:   "200",
				Result: ids.Ids,
			})
		} else {
			ctx.JSON(http.StatusOK, &models.DeleteResult{
				Msg:    "删除失败",
				Code:   "400",
				Result: []int{0},
			})
		}
	}
}
